package org.wang.generalcode.support.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
import java.nio.charset.StandardCharsets;

/**
 * 文件工具类
 */
@Slf4j
public class FileUtils {

    /**
     * 文件存储根路径
     */
    private static final String STORAGE_PATH = "storage/documents";

    /**
     * 保存文件
     *
     * @param file 文件对象
     * @return 文件路径
     */
    public static String saveFile(MultipartFile file) throws IOException {
        // 1. 生成存储路径
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        String fileName = UUID.randomUUID().toString().replace("-", "") + "." + getExtension(file.getOriginalFilename());
        String relativePath = STORAGE_PATH + "/" + datePath + "/" + fileName;
        
        // 2. 创建目录
        Path dirPath = Paths.get(STORAGE_PATH, datePath);
        Files.createDirectories(dirPath);
        
        // 3. 保存文件
        Path filePath = Paths.get(relativePath);
        Files.copy(file.getInputStream(), filePath);
        
        return relativePath;
    }

    /**
     * 删除文件
     *
     * @param filePath 文件路径
     */
    public static void deleteFile(String filePath) throws IOException {
        if (filePath != null) {
            Path path = Paths.get(filePath);
            Files.deleteIfExists(path);
        }
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName 文件名
     * @return 扩展名
     */
    public static String getExtension(String fileName) {
        if (fileName == null) {
            return "";
        }
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
    }

    /**
     * 读取文本文件内容
     *
     * @param filePath 文件路径
     * @return 文件内容
     */
    public static String readTextFile(String filePath) throws IOException {
        return Files.readString(Paths.get(filePath), StandardCharsets.UTF_8);
    }
} 